const app = getApp(); // Ensure app is defined

Page({
  data: {
    TabCur: 0,
    scrollLeft: 0,
    list: null,
    type: null,
    title: ""
  },
  onLoad(option) {
    var that = this;
    console.log("Type parameter:", option.type); // Add this line
    that.setData({
      type: option.type
    });
    if (option.type == 1) {
      that.setData({
        title: "搜索"
      })
    } else if (option.type == 2) {
      that.setData({
        title: "游戏推荐"
      })
    } else if (option.type == 3) {
      that.setData({
        title: "游戏预约"
      })
    } else if (option.type == 4) {
      that.setData({
        title: "高分游戏"
      })
    }
    var userId = app.globalData.userId;
    wx.request({
        url: app.globalData.local_url + 'api/getListGame',
        data: {
          title: "",
          type: that.data.type,
          userId: app.globalData.userId
        },
        method: 'GET',
        header: {
          'content-type': 'application/json'
        },
        success: function (res) {
          console.log("API Response:", res);
          if (res.data.code == 200) {
            if (res.data.data && res.data.data.length > 0) {
              console.log("Data received:", res.data.data);
              that.setData({
                list: res.data.data
              });
            } else {
              console.log("No data available for this type.");
              that.setData({
                list: []
              });
            }
          } else {
            console.error('Error fetching data:', res.data.message);
          }
        },
        fail: function (err) {
          console.error('API Request Failed:', err);
        }
      });
    },
  search(e) {
    var that = this;
    var val = e.detail.value;
    wx.request({
      url: app.globalData.local_url + 'api/getListGame',
      data: {
        title: val,
        type: that.data.type,
        userId: app.globalData.userId // Ensure userId is defined
      },
      method: 'GET',
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        if (res.data.code == 200) {
          if (res.data.data.length === 0) {
            console.log("No data available for this type.");
            // Handle the case where no data is returned
            that.setData({
              list: []
            });
          } else {
            that.setData({
              list: res.data.data
            });
          }
        } else {
          console.error('Error fetching search data:', res.data.message); // Log any errors
        }
      },
      fail: function (err) {
        console.error('Search API Request Failed:', err); // Log request failures
      }
    });
  },
  goInfo(e) {
    var id = e.currentTarget.dataset.id;
    console.log("Navigating to game info with ID:", id); // Add this line
    wx.navigateTo({
      url: '/pages/activity/info/info?id=' + id
    });
  }
  
});
